<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-10-06
 * Time: 01:13
 */

namespace app\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Models\WechatUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class SetPriceController extends Controller
{
    public function getIndex(Request $request)
    {
        $wechatUpload = WechatUpload::query()
            ->where('id', $request->id)
            ->where('openid', Session::get('wechat_openid'))
            ->first();
        if (null === $wechatUpload) {
            abort(404);
        }
        return view('wechat.set-price', compact('wechatUpload'));
    }

    public function postIndex(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'min_price' => 'required|numeric|min:0.01',
            'max_price' => 'required|numeric|min:0.01',
            'openid' => 'required',
            'key' => 'required',
            'id' => 'required|int',
        ]);
        $wechatUpload = WechatUpload::query()
            ->where('id', $request->id)
            ->where('openid', Session::get('wechat_openid'))
            ->where('key', $request->key)
            ->first();
        if (null === $wechatUpload) {
            abort(404);
        }
        $wechatUpload->title = $request->title;
        $wechatUpload->min_price = $request->min_price;
        $wechatUpload->max_price = $request->max_price;
        if ($wechatUpload->status == 2) {
            $wechatUpload->status = 0;
        }
        $wechatUpload->save();
        if (in_array($wechatUpload->type, [1, 2])) {
            $redirect_url = '/wechat/reward?id=' . $wechatUpload->id;
        } else {
            $redirect_url = '/wechat/member-center';
        }
        return redirect($redirect_url);
    }
}